﻿using System;
using System.Collections.Generic;
using System.Linq;
using Eric.SerialPorts;

namespace SerialPortWrappers.Test.Services
{
    public class TestDataVerifier : DataVerifier
    {
        public static byte[] DataHeader = { 0xEE, 0x44 };
        private const int CommandLen = 5;

        public override byte[] PushOneSingleCommandFromBegin(IList<byte> rawBytes)
        {
            if (rawBytes.Count < CommandLen)
                return null;
            var startIndex = IndexOfHeader(rawBytes.ToArray());
            if (startIndex < 0)
            {
                //Junk bytes, just clear it .
                rawBytes.Clear();
                return null;
            }

            var bizDataEndIndex = CommandLen + startIndex - 1;
            if (bizDataEndIndex > rawBytes.Count - 1)
            {
                ((List<byte>)rawBytes).RemoveRange(0, startIndex);
                return null;
            }

            var singleCommand = new byte[CommandLen];
            ((List<byte>)rawBytes).CopyTo(startIndex, singleCommand, 0, CommandLen);

            ((List<byte>)rawBytes).RemoveRange(0, startIndex);
            startIndex = IndexOfHeader(rawBytes.ToArray());
            ((List<byte>)rawBytes).RemoveRange(startIndex, CommandLen);

            return singleCommand;
        }

        public override byte[] EncodeBizData(byte[] bytesBiz)
        {
            var bytesFinal = new byte[DataHeader.Length + bytesBiz.Length];
            Buffer.BlockCopy(DataHeader, 0, bytesFinal, 0, DataHeader.Length);
            Buffer.BlockCopy(bytesBiz, 0, bytesFinal, DataHeader.Length, bytesBiz.Length);
            return bytesFinal;
        }

        public override byte[] DecodeBizData(byte[] bytes)
        {
            if (bytes == null)
                return null;
            var byteBiz = new byte[bytes.Length - DataHeader.Length];
            Buffer.BlockCopy(bytes, DataHeader.Length, byteBiz, 0, byteBiz.Length);
            return byteBiz;
        }

        public int IndexOfHeader(byte[] bytesSource)
        {
            return BytePatternSearcher.IndexOf(bytesSource, DataHeader);
        }
    }
}
